<script context="module">
  export async function preload(page, session) {
    if (!session.user) {
      this.error(403, "对不起，请登录之后再使用发布功能！");
      return;
    }
  }
</script>

<script>
  let title = '';
  let disabled = false;
  let error;
  import { stores, goto } from "@sapper/app";
  const post = async () => {
    if (title.length == 0) {
      error = "商品分类名称为必填项！";
      return;
    }
    disabled = true;
    const response = await fetch("/api2/productcategories", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        title
      }),
    }).catch((err) => {
      console.log(err);
      disabled = false;
    });
    disabled = false;
    const parsed = await response.json();
    if (parsed.success == 0) {
      error = parsed.message;
    } else if (parsed.success == 1) {
      await goto("/productcategories");
    }
  };
</script>

<svelte:head>
  <title>新增商品分类</title>
</svelte:head>
<div class="panel-header panel-header-sm" />
<div class="content">
  <div class="row">
    <div class="col-md-4 order-md-1 mb-4">
      <div class="card shadow">
        <div class="card-header">
          <h5 class="title">提示</h5>
        </div>
        <div class="card-body">
          <p>一、分类可按大分类，例如：油漆、门窗、油漆、墙纸等。</p>
          <p>
            二、分类也可细分小分类，例如：高档墙纸、中档墙纸、低端墙纸！
          </p>
          <p>三、创建好分类之后，创建库存商品时可选择对应分类。</p>
        </div>
      </div>
    </div>
    <div class="col-md-8 mx-auto">
      <div class="card shadow">
        <div class="card-header">
          <h5 class="title">新增商品分类</h5>
        </div>
        <div class="card-body">
          <form on:submit|preventDefault={post} action="post">
            <div class="form-group row">
              <label class="col-sm-2 col-form-label" for="title">分类名称</label
              >
              <div class="col-sm-10">
                <input
                  type="text"
                  id="title"
                  class="form-control"
                  placeholder="商品分类名称"
                  bind:value={title}
                />
              </div>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary" {disabled}
                >提交新增</button
              >
            </div>
          </form>
          {#if error}
            <div class="row">
              <div class="col-md-12">
                <p class="text-danger">{error}</p>
              </div>
            </div>
          {/if}
        </div>
      </div>
    </div>
  </div>
</div>
